package freecomm.fileexplorer;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/**  
 * FileCopy  
 *   
 * @author: Junwei.Xu  
 */
public class FileCopy
{
    /**  
     * copy file
     * @param sourceFile - the file which will be copied
     * @param targetFile - the file which will be copied  to
     * @throws IOException   
     * @return void  
     * @exception   
    */

    public static void copyFile(File sourceFile, File targetFile)
            throws IOException
    {
        /* new the file input stream and it's buffer stream */
        FileInputStream input = new FileInputStream(sourceFile);
        BufferedInputStream inBuff = new BufferedInputStream(input);

        /* new the file output stream and it's buffer stream */
        FileOutputStream output = new FileOutputStream(targetFile);
        BufferedOutputStream outBuff = new BufferedOutputStream(output);

        /* buffer array */
        byte[] b = new byte[1024 * 5];
        int len;
        while ((len = inBuff.read(b)) != -1)
        {
            outBuff.write(b, 0, len);
        }
        /* refresh output buffer stream */
        outBuff.flush();

        /* close all stream */
        inBuff.close();
        outBuff.close();
        output.close();
        input.close();
    }

    /**  
     * copy directory
     * @param sourceDir - the directory which will be copied
     * @param targetDir - the directory which will be copied  to
     * @throws IOException   
     * @return void  
     * @exception   
    */
    public static void copyDirectiory(String sourceDir, String targetDir)
            throws IOException
    {
        /* new target directory */
        (new File(targetDir)).mkdirs();
        /* get file list of current path */
        File[] file = (new File(sourceDir)).listFiles();
        for (int i = 0; i < file.length; i++)
        {
            if (file[i].isFile())
            {
                /* source file */
                File sourceFile = file[i];
                /* target file */
                File targetFile = new File(
                        new File(targetDir).getAbsolutePath() + File.separator
                                + file[i].getName());
                copyFile(sourceFile, targetFile);
            }
            if (file[i].isDirectory())
            {
                /* the folder which will be copied */
                String dir1 = sourceDir + "/" + file[i].getName();
                /* the folder which will be copied to */
                String dir2 = targetDir + "/" + file[i].getName();
                copyDirectiory(dir1, dir2);
            }
        }
    }
}
